package cn.zwy.json;

import java.io.File;
import java.io.FileOutputStream;

import org.objectweb.asm.*;

public class MyJsonDump implements Opcodes {

    public static void main(String[] args) throws Exception {
        byte[] b2 = dump(); // b2 与 b1 表示同一个类
        File file = new File("D:\\myapp\\otherlib\\", "MyJson.class");
        System.out.println(file.getPath());
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(b2, 0, b2.length);
        fos.flush();
        fos.close();
    }

    public static byte[] dump() throws Exception {
        ClassWriter cw = new ClassWriter(0);
        MethodVisitor mv;
        cw.visit(52, ACC_PUBLIC + ACC_SUPER, "cn/zwy/json/MyJson", null, "java/lang/Object", null);
        {
            mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            Label l0 = new Label();
            mv.visitLabel(l0);
            mv.visitLineNumber(5, l0);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
            mv.visitInsn(RETURN);
            Label l1 = new Label();
            mv.visitLabel(l1);
            mv.visitLocalVariable("this", "Lcn/zwy/json/MyJson;", null, l0, l1, 0);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }
        {
            mv = cw.visitMethod(ACC_PRIVATE + ACC_STATIC, "createClass", "(Ljava/lang/Object;Ljava/lang/String;)V",
                    null, null);
            mv.visitCode();
            Label l0 = new Label();
            mv.visitLabel(l0);
            mv.visitLineNumber(7, l0);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitTypeInsn(CHECKCAST, "cn/zwy/bean/UserBean");
            mv.visitVarInsn(ASTORE, 2);
            Label l1 = new Label();
            mv.visitLabel(l1);
            mv.visitLineNumber(8, l1);
            mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
            mv.visitVarInsn(ALOAD, 2);
            mv.visitMethodInsn(INVOKEVIRTUAL, "cn/zwy/bean/UserBean", "getId", "()Ljava/lang/String;", false);
            mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
            Label l2 = new Label();
            mv.visitLabel(l2);
            mv.visitLineNumber(9, l2);
            mv.visitInsn(RETURN);
            Label l3 = new Label();
            mv.visitLabel(l3);
            mv.visitLocalVariable("obj", "Ljava/lang/Object;", null, l0, l3, 0);
            mv.visitLocalVariable("attr", "Ljava/lang/String;", null, l0, l3, 1);
            mv.visitLocalVariable("convertObj", "Lcn/zwy/bean/UserBean;", null, l1, l3, 2);
            mv.visitMaxs(2, 3);
            mv.visitEnd();
        }
        cw.visitEnd();

        return cw.toByteArray();
    }
}
